<template>
  <div class="multimedia-history">
    <div class="main-content">
      <el-card class="history-card">
        <template #header>
          <div class="card-header">
            <h2>多媒体资源历史记录</h2>
            <div class="header-controls">
              <span class="page-info">第 {{ currentPage }} 页 / 每页15条 / 共 {{ total }} 条</span>
              <div class="custom-pagination">
                <el-button 
                  size="small" 
                  :disabled="currentPage <= 1" 
                  @click="jumpToPage(currentPage - 1)"
                >
                  上一页
                </el-button>
                <span class="page-number">{{ currentPage }}</span>
                <el-button 
                  size="small" 
                  :disabled="currentPage >= Math.ceil(total / 15)" 
                  @click="jumpToPage(currentPage + 1)"
                >
                  下一页
                </el-button>
              </div>
              <el-button type="primary" @click="fetchHistoryRecords" :loading="loading">刷新</el-button>
            </div>
          </div>
        </template>
        <div class="history-list" v-loading="loading">
          <div v-if="historyRecords.length === 0 && !loading" class="empty-tip">
            暂无历史记录
          </div>
          <div v-for="(record, index) in historyRecords" 
               :key="index" 
               class="history-item"
               @click="viewHistoryDetail(record)">
            <div class="history-item-header">
              <div class="media-type-and-title">
                <el-tag size="small" :type="getResourceTypeTag(record.resourceType)">
                  {{ formatResourceType(record.resourceType) }}
                </el-tag>
                <span class="history-title">{{ record.title }}</span>
              </div>
              <span class="history-time">{{ record.time }}</span>
            </div>
            <div class="history-content">
              <div v-if="record.resourceType.includes('image')" class="image-preview">
                <el-image 
                  :src="record.url" 
                  fit="cover"
                  :preview-src-list="[record.url]"
                  style="width: 100px; height: 75px; border-radius: 4px;"
                  :z-index="3000"
                  hide-on-click-modal
                />
              </div>
              <div class="content-description">{{ record.description || '暂无描述' }}</div>
            </div>
            <div class="history-item-footer">
              <div class="subject-grade">
                <span class="subject-tag">{{ record.subject }}</span>
                <span class="grade-tag">{{ record.grade }}</span>
              </div>
              <span class="topic-tag">{{ record.topic }}</span>
            </div>
          </div>
          <!-- 添加底部空白区域 -->
          <div class="bottom-space"></div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { safeGetItem, cleanupInvalidStorageValues } from '@/utils/storageUtils'

const historyRecords = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(15)
const total = ref(10) // 默认设置为10，确保分页组件始终显示

// 直接跳转到指定页面
const jumpToPage = (page) => {
  console.log('跳转到页面:', page)
  if (page < 1 || page > Math.ceil(total.value / 15)) {
    console.log('页码超出范围，忽略')
    return
  }
  
  if (page === currentPage.value) {
    console.log('当前已是第', page, '页，忽略')
    return
  }
  
  // 更新页码
  currentPage.value = page
  
  // 显示加载中
  loading.value = true
  historyRecords.value = []
  
  // 显示提示
  ElMessage.info({
    message: `正在加载第${page}页数据...`,
    duration: 1000
  })
  
  // 直接调用获取数据
  fetchHistoryRecordsForPage(page)
}

// 为特定页面获取历史记录，绕过缓存
const fetchHistoryRecordsForPage = async (page) => {
  loading.value = true
  
  try {
    // 确保localStorage中没有无效值
    cleanupInvalidStorageValues();
    
    // 使用safeGetItem安全获取teacherId，确保不会得到"undefined"字符串
    const teacherId = safeGetItem('teacherId');
    
    // 如果没有有效的teacherId，显示警告
    if (!teacherId) {
      console.warn('未找到有效的教师ID，可能需要重新登录');
    }
    
    console.log('多媒体资源历史请求使用的教师ID:', teacherId);
    
    // 直接使用原始axios请求，避免可能的缓存问题
    const timestamp = new Date().getTime()
    const response = await request({
      url: `/api/media-resources/history?_t=${timestamp}`,
      method: 'get',
      params: {
        teacherId: teacherId,
        page: page,
        size: 15
      }
    })
    
    console.log(`获取第${page}页数据响应:`, response)
    
    // 处理响应
    if (response.data && response.data.code === 200 && Array.isArray(response.data.data)) {
      // 记录ID，检查是否有变化
      const recordIds = response.data.data.map(item => item.id).join(',')
      console.log(`第${page}页记录ID: ${recordIds}`)
      
      historyRecords.value = response.data.data.map(item => ({
        id: item.id,
        subject: item.subject,
        grade: item.grade,
        topic: item.topic,
        resourceType: item.resourceType,
        title: item.title,
        description: item.description,
        url: item.url,
        format: item.format,
        duration: item.duration,
        time: new Date(item.createdTime).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      }))
      
      total.value = response.data.total || historyRecords.value.length
    } else {
      console.error('响应格式不正确:', response)
      ElMessage.error('获取数据失败：格式不正确')
    }
  } catch (error) {
    console.error('获取历史记录失败:', error)
    ElMessage.error('获取历史记录失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 获取历史记录（默认获取第一页）
const fetchHistoryRecords = async () => {
  currentPage.value = 1
  fetchHistoryRecordsForPage(1)
}

// 查看历史记录详情
const viewHistoryDetail = (item) => {
  // 根据资源类型显示不同内容
  let contentHtml = '';
  
  if (item.resourceType.includes('image')) {
    contentHtml = `
      <div style="text-align: center; margin-bottom: 20px;">
        <img src="${item.url}" style="max-width: 100%; max-height: 400px; border-radius: 8px;" />
      </div>
    `;
  } else if (item.resourceType.includes('video')) {
    contentHtml = `
      <div style="text-align: center; margin-bottom: 20px;">
        <video controls style="max-width: 100%; max-height: 400px; border-radius: 8px;">
          <source src="${item.url}" type="video/${item.format || 'mp4'}">
          您的浏览器不支持视频播放
        </video>
      </div>
    `;
  }
  
  ElMessageBox.alert(
    `<div style="font-size:15px;line-height:1.6;">
      <div style="margin-bottom:15px;"><strong>标题：</strong>${item.title}</div>
      ${contentHtml}
      <div style="margin-bottom:8px;"><strong>描述：</strong>${item.description || '暂无描述'}</div>
      <div style="margin-bottom:8px;"><strong>科目：</strong>${item.subject}</div>
      <div style="margin-bottom:8px;"><strong>年级：</strong>${item.grade}</div>
      <div style="margin-bottom:8px;"><strong>主题：</strong>${item.topic}</div>
      <div style="margin-bottom:8px;"><strong>资源类型：</strong>${formatResourceType(item.resourceType)}</div>
      ${item.duration ? `<div style="margin-bottom:8px;"><strong>时长：</strong>${formatDuration(item.duration)}</div>` : ''}
      <div style="margin-bottom:8px;"><strong>格式：</strong>${item.format || '未知'}</div>
      <div style="margin-bottom:8px;"><strong>URL：</strong><a href="${item.url}" target="_blank" style="color: #409EFF; text-decoration: underline;">${item.url}</a></div>
      <div><strong>创建时间：</strong>${item.time}</div>
    </div>`,
    '多媒体资源详情',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '关闭',
      customClass: 'media-detail-dialog'
    }
  )
}

// 格式化资源类型
const formatResourceType = (type) => {
  if (!type) return '未知类型';
  
  if (type.includes('image')) return '图片';
  if (type.includes('video')) return '视频';
  if (type.includes('audio')) return '音频';
  
  return type;
}

// 获取资源类型标签样式
const getResourceTypeTag = (type) => {
  if (!type) return '';
  
  if (type.includes('image')) return 'success';
  if (type.includes('video')) return 'danger';
  if (type.includes('audio')) return 'warning';
  
  return 'info';
}

// 格式化时长（秒转为分:秒）
const formatDuration = (seconds) => {
  if (!seconds) return '未知';
  
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  
  return `${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`;
}

// 添加全局样式
const globalStyle = document.createElement('style');
globalStyle.textContent = `
.media-detail-dialog .el-message-box__content {
  max-height: 70vh;
  overflow-y: auto;
}
.media-detail-dialog .el-message-box {
  width: 80%;
  max-width: 800px;
}
.media-detail-dialog .el-message-box__message p {
  margin: 0;
  line-height: 1.6;
}
`;
document.head.appendChild(globalStyle);

onMounted(() => {
  // 加载第一页历史记录数据
  fetchHistoryRecords()
})
</script>

<style scoped>
.multimedia-history {
  max-width: 1600px;
  margin: 0 auto;
}

.main-content {
  flex: 1;
  min-width: 0;
  height: auto;
  overflow-y: visible;
}

.history-card {
  height: auto;
  min-height: calc(100vh - 140px);
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.history-list {
  max-height: calc(100vh - 190px);
  height: auto;
  overflow-y: auto;
  padding: 10px 10px 25px 10px;
  margin-bottom: 20px;
}

.history-item {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.history-item:last-child {
  margin-bottom: 30px;
}

.history-item:hover {
  background-color: #f5f7fa;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.history-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.media-type-and-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.history-title {
  font-weight: 600;
  color: #303133;
  font-size: 16px;
}

.history-time {
  font-size: 12px;
  color: #909399;
}

.history-content {
  display: flex;
  gap: 15px;
  margin-bottom: 12px;
}

.content-description {
  flex: 1;
  font-size: 14px;
  color: #606266;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.history-item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.subject-grade {
  display: flex;
  gap: 8px;
}

.subject-tag, .grade-tag {
  font-size: 12px;
  color: #606266;
  background-color: #f4f4f5;
  padding: 2px 8px;
  border-radius: 4px;
}

.topic-tag {
  font-size: 12px;
  color: #909399;
  background-color: #f4f4f5;
  padding: 2px 8px;
  border-radius: 4px;
}

.empty-tip {
  text-align: center;
  padding: 40px 0;
  color: #909399;
  font-size: 14px;
}

.bottom-space {
  height: 30px;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
  font-weight: 600;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 15px;
}

.page-info {
  font-size: 13px;
  color: #606266;
  white-space: nowrap;
}

.custom-pagination {
  display: flex;
  align-items: center;
  gap: 10px;
  background: #f5f7fa;
  padding: 5px 10px;
  border-radius: 4px;
}

.page-number {
  font-size: 14px;
  font-weight: bold;
  color: #409EFF;
  min-width: 24px;
  text-align: center;
}

/* 添加滚动条样式 */
.history-list::-webkit-scrollbar {
  width: 6px;
}

.history-list::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.history-list::-webkit-scrollbar-track {
  background-color: transparent;
}
</style> 